package com.amigo.online.provider.adv.service.impl;

import java.util.List;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.amigo.online.common.core.response.Response;
import com.amigo.online.provider.adv.service.FeignResponseConvertService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class FeignResponseConvertServiceImpl implements FeignResponseConvertService {

    @Override
    public boolean convertBasicObject(ResponseEntity<Response> res, Object toValueType) {
        if (res.getStatusCodeValue() != 200) {
            return false;
        }
        if (res.getBody() == null) {
            return false;
        }
        if (res.getBody().getMeta().getCode() != 200) {
            return false;
        }
        Object responseData = res.getBody().getData();
        if (responseData == null) {
            return false;
        }

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        toValueType = objectMapper.convertValue(objectMapper, toValueType.getClass());
        return true;
    }

    @Override
    public boolean convertListObject(ResponseEntity<Response> res, Object toValueType) {
        if (res.getStatusCodeValue() != 200) {
            return false;
        }
        if (res.getBody() == null) {
            return false;
        }
        if (res.getBody().getMeta().getCode() != 200) {
            return false;
        }
        Object responseData = res.getBody().getData();
        if (responseData == null) {
            return false;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        toValueType = objectMapper.convertValue(objectMapper, new TypeReference<List<Object>>() {
        });
        return true;
    }
}
